
package org.jxls.builder.xml;

import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import org.jxls.area.Area;
import org.jxls.command.ImageCommand;
import org.jxls.common.AreaRef;
import org.jxls.common.ImageType;
import org.xml.sax.Attributes;

/**
 * @Fixed 解析image标签
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/18 16:16
 * @Modified By:
 */
public class ImageAction extends Action {

    public static final String SRC_ATTR = "src";
    public static final String IMAGE_TYPE_ATTR = "imageType";
    public static final String REF_ATTR = "ref";

    @Override
    public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException {
        String src = attributes.getValue(SRC_ATTR);
        String imageType = attributes.getValue(IMAGE_TYPE_ATTR);
        String ref = attributes.getValue(REF_ATTR);
        if (src == null || src.length() == 0) {
            String errMsg = "'src' attribute of 'image' tag is empty";
            ic.addError(errMsg);
            throw new IllegalArgumentException(errMsg);
        }
        if (ref == null || ref.length() == 0) {
            String errMsg = "'ref' attribute of 'image' tag is empty";
            ic.addError(errMsg);
        }
        if (imageType == null || imageType.length() == 0)
            imageType = ImageType.PNG.name();
        ImageCommand command = new ImageCommand(src, ImageType.valueOf(imageType));
        Object object = ic.peekObject();
        if (object instanceof Area) {
            Area area = (Area) object;
            area.addCommand(new AreaRef(ref), command);
        } else {
            String errMsg = "Object [" + object + "] currently at the top of the stack is not an Area";
            ic.addError(errMsg);
            throw new IllegalArgumentException(errMsg);
        }
        ic.pushObject(command);
    }

    @Override
    public void end(InterpretationContext ic, String name) throws ActionException {
        ic.popObject();
    }
}
